package encaps.action;

import encaps.entities.Grant;
import encaps.entities.UserLocal;
import encaps.entities.UserLocalHome;
import encaps.resources.Config;
import encaps.resources.Labels;
import encaps.resources.Response;
import encaps.utils.*;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import javax.ejb.FinderException;
import javax.naming.NamingException;
import org.jdom.Element;

public class ApplyProfileChangesAction extends EditProfileAction {

    public static final String APPLY_PROFILE_CHANGES = "applyProfileChanges";
    public static final String ROLE = "role";
    private UserLocal user;

    public ApplyProfileChangesAction(ActionContext context, Grant requiredGrant) {
        super(context, requiredGrant);
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            String oldLogin = actionContext.getUserLogin();
            UserLocalHome userHome = EntityUtil.getUserHome();
            user = userHome.findByLogin(oldLogin);

            Element dataToReEnter = validatePassword(user);
            if (dataToReEnter != null) {
                return dataToReEnter;
            }

            String newPassword = actionContext.getTextParameter(NEW_PASSWORD);
            String info = actionContext.getTextParameter(INFO);
            String email = actionContext.getTextParameter(EMAIL);
            String contacts = actionContext.getTextParameter(CONTACTS);

            String picName = String.format("%d-%s", user.getID(), user.getLogin());
            String picPath = IOHelper.uploadFile(actionContext, PICTURE, picName, Config.getUserImagesDirectory());

            if (!StringUtil.isEmpty(actionContext.getTextParameter(NEW_PASSWORD))) {
                user.setPassword(newPassword);
            }
            user.setInfo(info);
            user.setEmail(email);
            user.setContacts(contacts);
            if (picPath != null) {
                user.setAvatar(picPath);
            }

            return XMLHelper.createTextMessage("Profile changed");
        } catch (NoSuchAlgorithmException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        } catch (UnsupportedEncodingException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        } catch (SystemException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        } catch (FinderException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        } catch (NamingException ex) {
            throw new ActionExecutionException("Cannot execute action", ex);
        }
    }

    private Element validatePassword(UserLocal user) throws SystemException {
        String oldPassword = actionContext.getTextParameter(OLD_PASSWORD);
        String newPassword = actionContext.getTextParameter(NEW_PASSWORD);

        if (StringUtil.isEmpty(oldPassword) && StringUtil.isEmpty(newPassword)) {
            return null;
        }

        try {
            boolean oldPasswordRight =
                    user.getPasswordHash().equals(MD5Hash.getHash(oldPassword));
            boolean newPasswordEmpty = StringUtil.isEmpty(newPassword);

            if (oldPasswordRight && !newPasswordEmpty) {
                return null;
            }

            String noNewPassMessage = null;
            String wrongOldPassMessage = null;
            if (newPasswordEmpty) {
                noNewPassMessage = Labels.getLabel(Labels.ENTER_NEW_PASSWORD_MESSAGE);
            }
            if (!oldPasswordRight) {
                wrongOldPassMessage = Labels.getLabel(Labels.WRONG_OLD_PASSWORD_MESSAGE);
            }

            Element response = XMLHelper.createElement(Response.RESPONSE);
            Element e = XMLHelper.addChild(response, Response.ENTITY);
            e.setAttribute(Response.EDIT, "true");

            XMLHelper.addChild(e, XMLHelper.createHeader(Labels.getLabel(Labels.EDIT_PROFILE)));
            XMLHelper.addChild(e, XMLHelper.createImage(user.getAvatar(), PICTURE));
            XMLHelper.addChild(e, XMLHelper.createPasswordField(Labels.getLabel(Labels.OLD_PASSWORD), OLD_PASSWORD, wrongOldPassMessage));
            XMLHelper.addChild(e, XMLHelper.createPasswordField(Labels.getLabel(Labels.NEW_PASSWORD), NEW_PASSWORD, noNewPassMessage));
            XMLHelper.addChild(e, XMLHelper.createTextArea(Labels.getLabel(Labels.INFO), actionContext.getTextParameter(INFO), INFO));
            XMLHelper.addChild(e, XMLHelper.createTextField(Labels.getLabel(Labels.EMAIL), actionContext.getTextParameter(EMAIL), EMAIL));
            XMLHelper.addChild(e, XMLHelper.createTextField(Labels.getLabel(Labels.CONTACTS), actionContext.getTextParameter(CONTACTS), CONTACTS));
            XMLHelper.addChild(e, XMLHelper.createButton(Labels.getLabel(Labels.APPLY), APPLY_PROFILE_CHANGES));

            return response;
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return null;
    }
}
